import { Notification }from "element-ui";
import store from "../store/index";


let socket= null;//实例对象
let lockReconnect  =false;//是否真正建立连接
let timeout  =20*1000;//20秒一次心跳
let timeoutQbj  = null;//心跳倒计时
let serverTimeout0bj = null;//服务心跳倒计时
let timeoutnum =null;//断开 连倒计时


const initWebSocket = async () => {
  console.log("token：",store.getters.token)

  if ("WebSocket" in window){
    const wsUrl = "ws://127.0.0.1:8080/chat/"+store.getters.token
    socket = new WebSocket(wsUrl);
    socket.onerror = webSocketOnError //发生错误所执行的函数
    socket.onmessage = webSocketOnMessage //接收服务器返回的数据
    socket.onclose = webSocketOnClose //关闭连接
    socket.onopen = webSocketOnOpen //建立连接
  }else {
    Notification.error({
      title:"错误",
      message:"您的的浏览器不支持websocket，请更换Chrome或者Firefox浏览器。"
    })
  }
}


//发生错误所执行的函数
const webSocketOnError = (e)=>{
  //重新连接
  //initWebSocket();
  //reconnect();
  console.log(e)
}
//重新连接
const reconnect=()=>{
  if (lockReconnect){
    return
  }
  lockReconnect = true
  //没有连接上会一直重连，设置延迟避免请求过多
  timeoutnum && clearTimeout(timeoutnum)

  timeoutnum = setTimeout(function () {
    //新连接
    initWebSocket()
    lockReconnect = false
  },1000)
}
//接收服务器返回的数据
const webSocketOnMessage=(e)=>{
  //window自定义事件
  window.dispatchEvent(
    new CustomEvent("onmessageWS",{
      detail:{
        //data: JSON.parse(e?.data),
        data: e?.data
      }
    })
  );
  //重置心跳
  //reset()
}

//重连
const webSocketOnClose = (e)=>{
  reconnect();
}
//断开连接
const close = ()=>{
  socket.close()
}

//重置心跳
const reset = ()=>{
  clearTimeout(timeoutQbj)
  clearTimeout(serverTimeout0bj)
  //重启心跳
  start()
}
//连接建立时触发
const webSocketOnOpen =()=>{
  //start()
  console.log("连接建立时触发")
}
//打开连接时候的方法
const start =()=>{
  timeoutQbj && clearTimeout(timeoutQbj)
  serverTimeout0bj && clearTimeout(serverTimeout0bj)
  timeoutQbj = setTimeout(function () {
    //这里发送一个心跳
    if (socket.readyState ==1 ){
      //如果正常连接
      //socket.send("heartbeat")
    }else{
      //重连
      reconnect()
    }

    serverTimeout0bj = setTimeout(function () {
      //超时关闭
      socket.close();
    },timeout)
  },timeout)
}
//发送消息的方法
const sendWebSocket = (e)=>{
  socket.send(e)
}

export default {initWebSocket,sendWebSocket,webSocketOnMessage,close};
